const dbName = "dbUser";
let db = false;
console.log(dbName, "dbName");
const createDatabase = async () => {
  let version = 1;
  // 获取到所有数据库
  const databases = await window.indexedDB.databases();
  // 如果数据库表名重复，则version进行变化
  const preDatabase = databases.find(({ name }) => {
    name === dbName;
  });
  if (preDatabase) version = preDatabase.version;

  // create库
  const database = window.indexedDB.open(dbName, version);
  return new Promise((resolve, reject) => {
    database.onsuccess = (e) => {
      const rs = e.target.result;
      rs.onversionchange = () => {
        console.log("只能打开一个页面哦，请关闭其他页面再刷新哦");
      };
      // 建立事务
      const tx = rs.transaction("user", "readonly");
      const store = tx.objectStore("user");
      // 查询数据， 搜索一条数据
      const search = store.get(9);
      search.onsuccess = function () {
        const matching = search.result;
        if (matching !== undefined) {
          console.log(matching, "matching");
        } else {
          console.log(null);
        }
      };
      rs.close();
    };
    // 第一次打开成功后或者版本有变化自动执行以下事件：一般用于初始化数据库。
    database.onupgradeneeded = resolve;
    database.onerror = reject;
  });
};
const createTable = (db) => {
  return new Promise((resolve, reject) => {
    if (db.objectStoreNames) {
      // 判断表是否存在
      let objectStoreNames = Array.from(db.objectStoreNames);
      // 如果存在先执行删除表
      if (objectStoreNames.some((name) => name === "user")) {
        db.deleteObjectStore("user");
      }

      const table = db.createObjectStore("user", { keyPath: "id" });
      table.transaction.oncomplete = () => {
        const store = db.transaction("user", "readwrite").objectStore("user");
        // 创建数据，并给table插入数据
        let i = 0;
        while (i < 1000) {
          store.add({ id: i++, name: Math.floor(Math.random() * 100) });
        }
        resolve(i);
      };
      //   table.transaction.onerror = () => {
      //     reject();
      //   };
    }
  });
};

const start = async () => {
  const {
    target: { result },
  } = await createDatabase();
  const userData = await createTable((db = result));
  console.log(JSON.stringify(userData));
};

start();
